package nl.hanze.web.gba;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import nl.hanze.web.gba.dao.DAOFacade;
import nl.hanze.web.gba.doa.impl.DAOFacadeImpl;
import nl.hanze.web.gba.domain.NatuurlijkPersoon;
import nl.hanze.web.gba.logic.Logic;
import nl.hanze.web.gba.logic.security.AESCodec;

/**
 * Servlet implementation class GBA
 */
@WebServlet("/GBA")
public class GBA extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private DAOFacade facade;
	private Logic logic;
	private AESCodec codec;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GBA() {
        super();
        facade = new DAOFacadeImpl();
        codec = new AESCodec("moeilijkesleutel");
        logic = new Logic(facade, codec);
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action=readAction(request);
        if ("get".equals(action)) {
        	
        	String bsn = request.getParameter("bsn");
        	NatuurlijkPersoon np = null;
        	if(bsn != null){
        		/*
        		 * BSN gegeven, zoeken op BSN
        		 */
        		np = logic.getNatuurlijkPersoonbyBSN(Long.parseLong(bsn));
        	}
        	
        	if(np == null) {
        		/*
        		 * Geen BSN gegeven, leeg NP met BSN = -1 teruggeven
        		 */
        		np = new NatuurlijkPersoon();
        		np.setBsn(-1);
        	}
        	// return json format
            request.setAttribute("np", np);
            RequestDispatcher view=request.getRequestDispatcher("get.jsp");
            view.forward(request, response);
        }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*
		 * Message van de POST ophalen.
		 */
		StringBuilder stringBuilder = new StringBuilder();
		BufferedReader bufferedReader = null;
		try {
		  InputStream inputStream = request.getInputStream();
		  if (inputStream != null) {
		   bufferedReader = new BufferedReader(new InputStreamReader(
		inputStream));
		   char[] charBuffer = new char[128];
		   int bytesRead = -1;
		   while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
		    stringBuilder.append(charBuffer, 0, bytesRead);
		   }
		  } else {
		   stringBuilder.append("");
		  }
		} catch (IOException ex) {
		  throw ex;
		} finally {
		  if (bufferedReader != null) {
		   try {
		    bufferedReader.close();
		   } catch (IOException ex) {
		    throw ex;
		   }
		  }
		}
		String status = "OK";
		String body = stringBuilder.toString();
		
		body = logic.decodeSHA(body);
		
		if(body != null){
			NatuurlijkPersoon np = logic.jsonToNatuurlijkPersoon(body);
			
			if(np == null) {
				/*
				 * Omzetten van JSON naar NatuurlijkPersoon-object is niet gelukt
				 */
	    		status = "NOT OK";
	    	}else if(!logic.addNatuurlijkPersoon(np)){
	    		/*
	    		 * Toevoegen van natuurlijkpersoon is niet gelukt
	    		 */
	    		status = "NOT OK";
	    	}
		}else{
			/*
			 * Decoderen van SHA string is niet gelukt
			 */
			status = "NOT OK";
		}
		
		status = logic.encodeSHA(new Gson().toJson(status));
		
    	// return json format
        request.setAttribute("status", status);
        RequestDispatcher view=request.getRequestDispatcher("post.jsp");
        view.forward(request, response);		
	}
	
	private String readAction(HttpServletRequest request) {
        return request.getParameter("action");
    }

}
